package com.appbee.gdata.picasa.client.ui;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.appbee.core.client.data.HasStringIdKeyProvider;
import com.appbee.core.client.modular.SettingsView;
import com.appbee.gdata.picasa.shared.PicasaRequestFactory;
import com.appbee.gdata.picasa.shared.SimpleAlbumProxy;
import com.google.gwt.core.client.GWT;
import com.google.gwt.text.shared.AbstractRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ValueListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;

@Singleton
public class PhotoShowSettingsView extends Composite implements SettingsView
{

	private static PhotoShowSettingsViewUiBinder uiBinder = GWT
			.create(PhotoShowSettingsViewUiBinder.class);

	interface PhotoShowSettingsViewUiBinder extends
			UiBinder<Widget, PhotoShowSettingsView>
	{
	}
	
	@UiField(provided = true)
	ValueListBox<SimpleAlbumProxy> albumList = new ValueListBox<SimpleAlbumProxy>(
			new AlbumRender(), new HasStringIdKeyProvider<SimpleAlbumProxy>());
	
	private List<SimpleAlbumProxy> albums;
	private String settingsString = null;

	@Inject
	public PhotoShowSettingsView(PicasaRequestFactory serviceProvider)
	{
		Request<List<SimpleAlbumProxy>> request = serviceProvider
				.getPicasaService().findAlbums();
		request.fire(new Receiver<List<SimpleAlbumProxy>>()
		{

			@Override
			public void onSuccess(List<SimpleAlbumProxy> response)
			{
				albums = response;
				albumList.setAcceptableValues(response);
				if (settingsString != null)
					setAlbumValue(settingsString);
			}

		});
		initWidget(uiBinder.createAndBindUi(PhotoShowSettingsView.this));
	}

	@Override
	public void setSettingsString(String settingsString)
	{
		this.settingsString = settingsString;
		if (albums != null)
		{
			setAlbumValue(settingsString);
		}
	}

	private void setAlbumValue(String settingsString)
	{
		SimpleAlbumProxy value = null;
		for (SimpleAlbumProxy album : albums)
		{
			if (album.getId().equals(settingsString))
				value = album;
		}
		albumList.setValue(value);
	}

	@Override
	public String toSettingsString()
	{
		SimpleAlbumProxy value = albumList.getValue();
		String setttingsString = value == null ? "" : value.getId();
		return setttingsString;
	}

	public class AlbumRender extends AbstractRenderer<SimpleAlbumProxy>
	{

		@Override
		public String render(SimpleAlbumProxy object)
		{
			return object == null ? "" : object.getTitle();
		}
		
		
	}
	
}
